package com.example.learn.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/*
*   上传图片工具类
* */
public class UploadUtils {
    private static final String BASE_URL = "F:\\java_workspace\\simple_learn_java\\src\\main\\resources\\static\\";

    private static final String SERVER_URL = "http://192.168.10.131:8888/static/";

    public static String upload(MultipartFile file){
        // 获得上传文件名
        String filename = file.getOriginalFilename();
        // 保证图片名称唯一性
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 拼接名称
        String newFilename = uuid + "-" + filename;
        // 创建文件实例
        File image = new File(BASE_URL, newFilename);
        // 对文件进行上传操作
        try {
            file.transferTo(image);
        } catch (IOException e) {
            return null;
        }
        return SERVER_URL + newFilename;
    }
}
